package com.lovi.net_.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端接收到客户端传过来的图片
 * 并向客户端发送“已经接收到图片”
 */
public class SocketTCPServer04 {
    public static void main(String[] args) throws IOException {
        //1.监听8099端口
        ServerSocket serverSocket = new ServerSocket(8099);
        System.out.println("服务端正在监听8099端口...");
        Socket socket = serverSocket.accept();
        //2.服务端接收到客户端传过来的图片
        //2.1 接受图片并写到磁盘里
        FileOutputStream fos = new FileOutputStream("D:\\Pictures\\壁纸\\2.png");
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //拿到图片的字符数组
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = bis.read(bytes)) != -1){
            fos.write(bytes,0,len);
        }
        fos.flush();
        //3.向客户端发送“已经接收到图片”
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("已经接收到图片");
        bw.newLine();//结束标志
        //统一关闭流
        bw.close();
        bis.close();
        fos.close();
        System.out.println("服务端关闭....");
    }
}
